﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json.Linq;

namespace SuperMan
{
    public partial class JsonNodeInput : Form
    {
        String oldname;
        JsonTreeNode node;
        public JsonNodeInput(JsonTreeNode node)
        {
            InitializeComponent();
            this.jsonValue.Text = node.jValue;
            this.jsonKey.Text = node.jKey;
            this.node = node;
            oldname = node.jKey;
        }


        private void submitButton_Click(object sender, EventArgs e)
        {
            node.jKey = jsonKey.Text;
            node.jValue = jsonValue.Text;
            if (node.Nodes.Count > 0)
            {
                node.Text = jsonKey.Text;
              
            }
            else {
               node.Text = jsonKey.Text  + " : " + jsonValue.Text;
            }

            updateJsonObj(node.jsonObject, jsonKey.Text, jsonValue.Text);

            this.DialogResult = DialogResult.OK;
        }



        void updateJsonObj(object obj,String name,String value) {

            if (obj.GetType() == typeof(JArray))
            {
                JArray jj = (JArray)obj;
                JArray njj = new JArray(name);
                foreach (var j in jj)
                {
                    njj.Add(j);
                }
                jj.Parent.Add( njj);
                jj.Remove();
            }
            else if (obj.GetType() == typeof(JObject))
            {
                JObject jj = (JObject)obj;
                JObject njj = new JObject(name);
                foreach (var j in jj)
                {
                    njj.Add(j);
                }
                jj.Parent.Add(njj);
                jj.Remove();
                
            }
            else
            {

                JProperty jj = (JProperty)obj;

                if (oldname == name)
                {
                    jj.Value = value;
                }
                else
                {
                    jj.Parent.Add(new JProperty(name, value));
                    jj.Remove();
                }
               
                

            }
        }
    }
}
